package com.wo.cloud.log.event;

import com.wo.cloud.core.entity.CommonLog;
import com.wo.cloud.kafka.channel.LogChannel;
import com.wo.cloud.log.feign.ICommonLogProvider;
import com.wo.cloud.log.feign.ISysLogFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/4/30 9:31
 * Description: 注解形式，异步监听事件
 */


@Slf4j
@AllArgsConstructor
@Component
public class LogListener {
    private final static Logger log = LoggerFactory.getLogger(LogListener.class);

    private final LogChannel logChannel;

    private final static int RETRY_TIMES = 3;
//    private ISysLogFeign sysLogFeign;

//    private ICommonLogProvider commonLogProvider;

//    public LogListener(ISysLogFeign sysLogFeign) {
//        this.sysLogFeign = sysLogFeign;
//    }
//
//    public LogListener(ICommonLogProvider commonLogProvider) {
//        this.commonLogProvider = commonLogProvider;
//    }

    // 开启事件监听
    @Async
    @Order
    @EventListener(classes = LogEvent.class)
    public void saveSysLog(LogEvent logEvent) {
        CommonLog commonLog = (CommonLog) logEvent.getSource();
        // 判断消息是否投递成功,进行投递重试默认重试三次

        boolean flag = logChannel.sendLogMessage().send(MessageBuilder.withPayload(commonLog).build());
        if (flag) {
            log.info("消息发送成功");
        }else {
            log.info("消息发送失败");
        }

        // 发送日志到kafka
//        while (!result && !(atomicInteger.get() >= RETRY_TIMES)) {
//        commonLogProvider.sendCommonLog(commonLog);
//        }
        // TODO: 直接将日志存入数据库
        // sysLogFeign.set(commonLog);
    }
}
